<!-- 账号管理页面 -->
<template>
  <div>
    <h2 style="float: left">账号管理</h2>
    <div id="add-account-btn" @click="addAccountClick">添加账号</div>
    <div style="clear: both"></div>
    <div class="title">
      <el-table
        class="table"
        v-loading="loadingAccountData"
        :data="
          tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        :stripe="true"
        :border="true"
        :header-cell-style="{ background: '#ECF8FD', color: '#000' }"
      >
        <el-table-column prop="number" label="序号"> </el-table-column>
        <el-table-column prop="account" label="账号"></el-table-column>
        <el-table-column prop="userId" label="用户编号"></el-table-column>
        <el-table-column prop="companyID" label="公司编号"></el-table-column>
        <el-table-column prop="authority" label="权限"></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建/修改时间"
        ></el-table-column>
        <el-table-column prop="action" label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="
                handleResetPassword(scope.$index, scope.row, scope.column)
              "
              >重置密码</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <br />
      <div class="pagination-block">
        <el-pagination
          background
          layout="prev, pager, next,jumper, ->, total"
          :total="tableData.length"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          style="text-align: center"
        >
        </el-pagination>
      </div>
      <div style="clear: both"></div>
    </div>
    <AddAccount v-if="showAddAccount" @close="closeAddAccount"></AddAccount>
    <ResetPassword
      v-if="showResetPassword"
      :accountInfo="selectAccountInfo"
      @close="closeResetPassword"
    ></ResetPassword>
  </div>
</template>

<script>
import AddAccount from "@/components/accountManage/AddAccount";
import ResetPassword from "@/components/accountManage/ResetPassword";
export default {
  name: "AccountManage",
  components: {
    AddAccount,
    ResetPassword,
  },
  data() {
    return {
      //是否展示添加账号界面
      showAddAccount: false,
      //是否展示重置密码界面
      showResetPassword: false,
      //用户信息数据加载
      loadingAccountData: false,
      selectAccountInfo: {},
      message: [],
      //用户信息数组
      tableData: [
        // {
        //   number: "1",
        //   account: "keyone666",
        //   user: "Admin",
        //   authority: "管理员",
        //   createTime: "2021-1-18 10:19",
        // },
      ],
      currentPage: 1,
      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      totalCount: 1,
      // 个数选择器（可修改）
      // pageSizes: [10, 20, 30, 40],
      // 默认每页显示的条数（可修改）
      pageSize: 9,
      loading: false,
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.getAllUser();
  },
  methods: {
    //获取所有用户
    getAllUser() {
      let that = this;
      this.tableData = [];
      this.loadingAccountData = true;
      this.$axiosRequest("/test", "post", this.$api.allUser, {}, true)
        .then((response) => {
          that.message = response.data.data;
          if (
            response.data.statusCode === 200 &&
            response.data.msg === "success"
          ) {
            let array = response.data.data;
            for (const key in array) {
              if (Object.hasOwnProperty.call(array, key)) {
                const element = array[key];
                let accountItem = {};
                accountItem.number = this.tableData.length + 1;
                accountItem.userId = element.id;
                accountItem.account = element.name;
                accountItem.companyID = element.companyID;
                accountItem.authority = this.getAuthority(element.level);
                accountItem.createTime = element.createDate;
                this.tableData.push(accountItem);
              }
            }
          } else {
            // this.$message.error(response.data.data);
            this.$alert(response.data.data, "错误", {
              confirmButtonText: "确定",
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          this.loadingAccountData = false;
        });
    },
    //根据用户level获得权限名称
    getAuthority(level) {
      switch (level) {
        case 1: {
          return "管理员";
        }
        case 5: {
          return "教师";
        }
        case 10: {
          return "学生";
        }
      }
    },
    closeAddAccount() {
      this.getAllUser();
      this.showAddAccount = false;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    addAccountClick() {
      this.showAddAccount = true;
    },
    handleResetPassword(index) {
      // this.selectAccountInfo = this.message[index];
      this.selectAccountInfo =
        this.message[(this.currentPage - 1) * this.pageSize + index];
      this.showResetPassword = true;
    },
    closeResetPassword() {
      this.getAllUser();
      this.showResetPassword = false;
    },
    handleDelete(row) {
      // console.log(index,x,y);
      let that = this;
      this.$axiosRequest(
        "/test",
        "post",
        this.$api.deleteUser,
        {
          uid: this.message[row.number - 1].id,
        },
        true
      )
        .then((response) => {
          if (
            response.data.statusCode === 200 &&
            response.data.msg === "success"
          ) {
            // this.$router.go(0);
            this.getAllUser();
            // that.$message.success("删除成功！");
            that.$alert("删除成功！", "成功", {
              confirmButtonText: "确定",
              type: "success",
            });
          } else {
            console.log("错误");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
<style scoped>
/* @import url(); 引入css类 */
#add-account-btn {
  text-align: center;
  line-height: 35px;
  float: right;
  width: 120px;
  height: 35px;
  background-color: #0386e0;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-block {
  float: right;
}
.title {
  padding: 25px;
  background-color: white;
}
.table {
  height: 527px;
  width: 100%;
}
</style>